package com.hdy.common.network;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;

public class HdyWifiManager {

	private static final String TAG = "[HdyWifiManager]";
	private WifiManager mWifiManager;
	private WifiLock mWifiLock;

	public HdyWifiManager(Context context) {
		mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		mWifiLock = mWifiManager.createWifiLock("mWifiLock");
		openWifi();
		startScan();
	}

	public boolean openWifi() {
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return mWifiManager.isWifiEnabled();
	}

	public void closeWifi() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
	}

	public void startScan() {
		if (mWifiManager != null) {
			if (!mWifiManager.isWifiEnabled()) {
				mWifiManager.setWifiEnabled(true);
			}
			mWifiManager.startScan();
		}
	}

	// 锁定wifiLock，在灭屏的时候不会关闭wifi
	public void acquireWifiLock() {
		if (mWifiLock != null) {
			mWifiLock.acquire();
		}
	}

	// 解锁wifiLock
	public void releaseWifiLock() {
		if (mWifiLock != null) {
			if (mWifiLock.isHeld()) {
				mWifiLock.release();
			}
		}
	}

	// 获取连接上的wifi，可能为空
	public WifiInfo getConnectionWifiInfo() {
		WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
		return mWifiInfo;
	}

	// 获取wifi列表
	public List<ScanResult> getWifiList() {
		return mWifiManager.getScanResults();
	}

	// 先断开当前wifi，再重新连接。这样连接成功之后就是连接到了信号最强的那个ap了
	public void disconnectAndreconnect() {
		mWifiManager.disconnect();
		mWifiManager.reconnect();
	}

	public void reconnect() {
		mWifiManager.reconnect();
	}

	// 清空所有wifi配置
	private void clearAllWifiConfi() {
		List<WifiConfiguration> existingConfigs = mWifiManager
				.getConfiguredNetworks();

		for (WifiConfiguration existingConfig : existingConfigs) {
			mWifiManager.disableNetwork(existingConfig.networkId);
			mWifiManager.removeNetwork(existingConfig.networkId);
		}
		mWifiManager.saveConfiguration();
	}

	// 连接wifi
	public void connectWifi(ScanResult scanResult, String password) {
		int wifiType = getWifiEncrypt(scanResult.capabilities);
		WifiConfiguration configuration = CreateWifiInfo(scanResult.SSID,
				password, wifiType);
		addNetwork(configuration);
	}

	// 添加一个网络配置并连接
	public void addNetwork(WifiConfiguration wcg) {
		int wcgID = mWifiManager.addNetwork(wcg);
		mWifiManager.enableNetwork(wcgID, true);
		// 保存wifi，下次关机再打开自动重连
		mWifiManager.updateNetwork(wcg);
		mWifiManager.saveConfiguration();
	}

	public WifiConfiguration CreateWifiInfo(String SSID, String Password,
			int Type) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";

		// wifi配置存在先删除
		WifiConfiguration tempConfig = this.IsExisted(SSID);
		if (tempConfig != null) {
			mWifiManager.removeNetwork(tempConfig.networkId);
		} else {
			Log.i(TAG, "IsExisted is null.");
		}

		if (Type == 1) // WIFICIPHER_NOPASS没密码的
		{
			config.wepKeys[0] = "\"" + "\"";
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 2) // WIFICIPHER_WEP
		{
			config.hiddenSSID = true;
			config.wepKeys[0] = "\"" + Password + "\"";
			config.allowedAuthAlgorithms
					.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 3) // WIFICIPHER_WPA一般的
		{
			config.preSharedKey = "\"" + Password + "\"";

			config.hiddenSSID = true;
			config.allowedAuthAlgorithms
					.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers
					.set(WifiConfiguration.PairwiseCipher.TKIP);
			// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers
					.set(WifiConfiguration.PairwiseCipher.CCMP);
			config.status = WifiConfiguration.Status.ENABLED;
		}
		return config;
	}

	// 当前选中的wifi是哪种加密方式
	// 传进的是ScanResult.capabilities
	public static int getWifiEncrypt(String capability) {
		StringBuilder sb = new StringBuilder();
		// 空的不懂类型
		if (TextUtils.isEmpty(capability)) {
			return -1;
		}
		// wep的加密类型是2
		if (capability.contains("WEP")) {
			sb.append("WEP");
			return 2;
		}
		// 其他是3
		if (capability.contains("WPA")) {
			sb.append("WPA");
			return 3;
		}
		if (capability.contains("WPA2")) {
			sb.append("/");
			sb.append("WPA2");
			return 3;
		}
		if (capability.contains("WPS")) {
			sb.append("/");
			sb.append("WPS");
			return 3;
		}
		// 开放的
		if (TextUtils.isEmpty(sb)) {
			return 1;
		}
		return -1;
	}

	// 查看是否已经配置过该SSID
	private WifiConfiguration IsExisted(String SSID) {
		List<WifiConfiguration> existingConfigs = mWifiManager
				.getConfiguredNetworks();
		for (WifiConfiguration existingConfig : existingConfigs) {
			if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
				return existingConfig;
			}
		}
		return null;
	}
}
